<template>
	<div v-if="pageType === 'i'" class="game-container report-container">
		<div class="view-container dealer-container">
			<div class="params">
				<el-form
					ref="form"
					:inline="true"
					:model="queryData"
					label-width="auto"
				>
					<el-form-item
						:label="$t('common.belong_merchant') + ':'"
						prop="merchantId"
					>
						<merchant-select
							v-model="queryData.merchantId"
							:placeholder="$t('common.all')"
						></merchant-select>
					</el-form-item>
					<el-form-item
						:label="$t('agent.contract_develop_time') + ':'"
						prop="time"
					>
						<el-date-picker
							v-model="loginTime"
							size="medium"
							:picker-options="pickerOptions"
							format="yyyy-MM-dd HH:mm:ss"
							type="datetimerange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							align="right"
							clearable
							:default-time="defaultTime"
						></el-date-picker>
					</el-form-item>
					<el-form-item>
						<el-input
							v-model="selectSearchVal"
							clearable
							size="medium"
							:placeholder="$t('common.please_enter')"
							@blur="trimSearchVal"
						>
							<el-select
								slot="prepend"
								v-model="selectSearchType"
								style="width: 150px"
								:placeholder="$t('common.please_choose')"
							>
								<el-option
									:label="$t('agent.sign_account')"
									:value="1"
								></el-option>
								<el-option
									:label="$t('common.direct_superior')"
									:value="2"
								></el-option>
								<el-option
									:label="
										$t('agent.contract_develop_account')
									"
									:value="3"
								></el-option>
							</el-select>
						</el-input>
					</el-form-item>
					<el-form-item :label="$t('agent.agent_level') + ':'">
						<el-select
							v-model="queryData.signProxyLevel"
							style="width: 120px"
							clearable
							collapse-tags
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in proxyLevelArr"
								:key="item.id"
								:label="item.proxyLevelArr"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('agent.operation_type') + ':'">
						<el-select
							v-model="queryData.dataSources"
							style="width: 120px"
							clearable
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in dataSourcesArr"
								:key="item.description"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('agent.effective_status') + ':'">
						<el-select
							v-model="queryData.effectStatus"
							style="width: 120px"
							clearable
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in effectStatusArr"
								:key="item.description"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('agent.contract_status') + ':'">
						<el-select
							v-model="queryData.contractStatus"
							style="width: 120px"
							clearable
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in contractStatusArr"
								:key="item.description"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						:label="$t('agent.policy_type') + ':'"
						prop="policyType"
					>
						<el-select
							v-model="queryData.policyTypeConfigId"
							style="width: 80%"
							clearable
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in policyTypeArr"
								:key="item.id"
								:label="item.policyType"
								:value="item.id"
							/>
						</el-select>
					</el-form-item>
					<el-form-item style="margin-left: 8px">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="loading"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="loading"
							size="medium"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
						<el-button
							v-if="hasPermission('201041')"
							icon="el-icon-folder"
							type="warning"
							:disabled="loading"
							size="medium"
							@click="create"
						>
							{{ $t('agent.add') }}
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div class="content">
				<el-table
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					class="small-size-table"
					:data="tableData"
					style="width: 100%"
					:header-cell-style="getRowClass"
					highlight-current-row
				>
					<el-table-column
						align="center"
						:label="$t('common.actions')"
						width="120"
						fixed="left"
					>
						<template slot-scope="scope">
							<el-link
								v-if="hasPermission('201047')"
								type="primary"
								@click="openDetail(scope.row)"
							>
								{{ $t('agent.view') }}
							</el-link>
							<el-link
								v-if="
									scope.row.effectStatus === 1 &&
										hasPermission('201046')
								"
								type="primary"
								style="margin-left:10px"
								@click="openEdit(scope.row)"
							>
								{{ $t('agent.reposition') }}
							</el-link>
							<el-link
								v-if="
									scope.row.effectStatus === 0 &&
										scope.row.signProxyLevel !== 0 &&
										hasPermission('201043')
								"
								type="primary"
								style="margin-left:10px"
								@click="openSignDialog(scope.row)"
							>
								{{ $t('agent.signatory') }}
							</el-link>
						</template>
					</el-table-column>
					<el-table-column
						prop="signProxyName"
						align="center"
						:label="$t('agent.sign_account')"
						min-width="130"
					>
						<template slot="header">
							{{ $t('agent.sign_account') }}
							<br />
							{{ $t('agent.agent_level') }}
						</template>
						<template slot-scope="scope">
							{{ scope.row.signProxyName }}
							<br />
							{{ scope.row.signProxyLevelId }}
						</template>
					</el-table-column>
					<el-table-column
						prop="parentProxyName"
						align="center"
						:label="$t('common.direct_superior')"
						min-width="130"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.parentProxyName || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="accountType"
						align="center"
						:label="$t('common.belong_merchant')"
						min-width="120"
					>
						<template slot-scope="scope">
							{{ merchantFilter(scope.row.merchantId) }}
						</template>
					</el-table-column>
					<el-table-column
						prop="dataSources"
						align="center"
						:label="$t('agent.operation_type')"
						min-width="130"
					>
						<template slot-scope="scope">
							<span>
								{{
									_typeFilter(
										scope.row.dataSources,
										'dataSourcesArr'
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="contractType"
						align="center"
						:label="$t('agent.contract_mode')"
						min-width="130"
					>
						<template slot-scope="scope">
							<span>
								{{
									typeFilter(
										scope.row.contractType,
										'contractType'
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="policyTypeConfigId"
						align="center"
						:label="$t('agent.policy_type')"
						min-width="130"
					>
						<template slot-scope="scope">
							<span>
								{{
									filterPolicyType(
										scope.row.policyTypeConfigId,
										scope.row.contractType
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						:label="$t('agent.commission_rates')"
						width="180"
					>
						<template slot-scope="scope">
							<span>
								{{
									filterRebateRatio(
										scope.row.beginRate,
										scope.row.endRate
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="contractStatus"
						align="center"
						:label="$t('agent.contract_status')"
						min-width="130"
					>
						<template slot-scope="scope">
							<span
								:class="
									scope.row.contractStatus === 1
										? 'lockingRgba'
										: 'disableRgba'
								"
							>
								{{
									typeFilter(
										scope.row.contractStatus,
										'contractStatusType'
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="effectStatus"
						align="center"
						:label="$t('agent.effective_status')"
						min-width="130"
					>
						<template slot-scope="scope">
							<span
								:class="
									scope.row.effectStatus === 1
										? 'lockingRgba'
										: 'disableRgba'
								"
							>
								{{
									typeFilter(
										scope.row.effectStatus,
										'effectStatusType'
									)
								}}
							</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="createDt"
						align="center"
						:label="$t('agent.contract_develop_time')"
						min-width="180"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.createDt || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="signDt"
						align="center"
						:label="$t('agent.sign_time')"
						min-width="180"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.signDt || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="lostEffectDt"
						align="center"
						:label="$t('agent.contract_expiry_time')"
						min-width="180"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.lostEffectDt || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="createAccount"
						align="center"
						:label="$t('agent.contract_develop_account')"
						min-width="130"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.createAccount || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="backNote"
						align="center"
						:label="$t('common.remark')"
						min-width="180"
					>
						<template slot-scope="scope">
							{{ scope.row.backNote || '-' }}
						</template>
					</el-table-column>
				</el-table>
				<el-pagination
					:current-page.sync="pageNum"
					class="pageValue"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="pageSizes"
					:total="total"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</div>
			<el-dialog
				:title="$t('agent.signatory')"
				:visible.sync="signDialog.visible"
				width="500px"
				top="20vh"
				@close="closeSignDialog"
			>
				<el-form
					ref="dialogForm"
					:model="signDialog.form"
					label-width="auto"
					size="normal"
					:rules="rules"
				>
					<el-form-item
						:label="$t('common.remark') + ':'"
						prop="remark"
					>
						<el-input
							v-model.trim="signDialog.form.remark"
							type="textarea"
							:maxlength="500"
							show-word-limit
							style="width:80%"
							:placeholder="$t('common.please_enter')"
							rows="3"
						></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer">
					<el-button @click="signDialog.visible = false">
						{{ $t('common.cancel') }}
					</el-button>
					<el-button
						:disabled="signDialog.loading"
						type="primary"
						@click="handleSign"
					>
						<i
							v-show="signDialog.loading"
							class="el-icon-loading"
						></i>
						<span>{{ $t('common.sure') }}</span>
					</el-button>
				</span>
			</el-dialog>
		</div>
	</div>
	<Detail
		v-else-if="pageType === 'd'"
		:detail-data="detailData"
		:pageType.sync="pageType"
		@goback="back"
	></Detail>
	<CreateOrEdit
		v-else
		:edit-data="editData"
		:pageType.sync="pageType"
		:is-edit="isEdit"
		@goback="back"
	></CreateOrEdit>
</template>

<script>
// 结合自己的UI,名称和功能、函数等
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import { filterEmptyParams } from '@/utils'
const startTime = () =>
	dayjs()
		.startOf('day')
		.valueOf()
const endTime = () =>
	dayjs()
		.endOf('day')
		.valueOf()

export default {
	name: routerNames.contract,
	components: {
		Detail: () => import('./components/Detail.vue'),
		CreateOrEdit: () => import('./components/CreateOrEdit.vue')
	},
	mixins: [list],
	data() {
		// this.loadData = this.throttle(this.loadData, 1000)
		// this._changeTableSort = this.throttle(this._changeTableSort, 1000)
		return {
			queryData: {
				contractStatus: undefined,
				contractType: undefined,
				createAccount: undefined,
				dataSources: undefined,
				effectStatus: undefined,
				parentProxyName: undefined,
				sginType: undefined,
				signProxyLevel: undefined,
				signProxyName: undefined,
				policyTypeConfigId: undefined
			},
			selectSearchVal: '',
			selectSearchType: 1,
			loginTime: [startTime(), endTime()],
			tableData: [],
			pageType: 'i',
			detailData: {},
			editData: {},
			signDialog: {
				visible: false,
				loading: false,
				form: {
					contractId: undefined,
					remark: undefined
				}
			},
			rules: {
				remark: [
					{
						required: true,
						message: this.$t('agent.rule_input_tip_remark'),
						trigger: 'blur'
					},
					{
						min: 2,
						max: 500,
						message: this.$t('agent.rule_length_tip2-500'),
						trigger: 'blur'
					}
				]
			},
			isEdit: false,
			proxyLevelArr: [],
			policyTypeArr: [],
			clonePolicyTypeArr: []
		}
	},
	computed: {
		// 操作类型
		dataSourcesArr() {
			return [
				{ code: '1', description: this.$t('agent.add') },
				{ code: '2', description: this.$t('agent.reposition') }
			]
		},
		// 契约模式
		contractTypeArr() {
			return this.globalDics.contractType || []
		},

		// 生效状态
		effectStatusArr() {
			return this.globalDics.effectStatusType || []
		},

		// 契约状态
		contractStatusArr() {
			return this.globalDics.contractStatusType || []
		},
		accountTypeArr() {
			return this.globalDics.accountType || []
		}
	},
	mounted() {
		this.getProxyLevelArr()
		this.getPolicyTypeArr(true)
	},
	methods: {
		trimSearchVal() {
			const value = this.selectSearchVal
			if (value) {
				this.selectSearchVal = value.replace(/\s*/g, '')
			}
		},
		getPolicyTypeArr(init = false) {
			this.queryData.policyTypeConfigId = undefined
			const contractType = this.queryData.contractType
				? this.queryData.contractType
				: undefined
			this.$api
				.getProxyMinContractPolicyTypeList({
					contractType
				})
				.then((res) => {
					if (res?.code === 200) {
						this.policyTypeArr = res.data || []
						this.policyTypeArr.push({
							id: 0,
							policyType: this.$t('agent.custom')
						})
						if (init) {
							this.clonePolicyTypeArr = JSON.parse(
								JSON.stringify(this.policyTypeArr)
							)
						}
					}
				})
		},
		filterPolicyType(policyTypeConfigId, contractType) {
			if (policyTypeConfigId === 0) {
				return this.$t('agent.custom')
			}
			const currentPolicyType = this.clonePolicyTypeArr?.find(
				(item) =>
					item.id === policyTypeConfigId &&
					item.contractType === contractType
			)
			return currentPolicyType?.policyType
				? currentPolicyType.policyType
				: '-'
		},
		getProxyLevelArr() {
			this.$api.getProxylevelnameList().then((res) => {
				this.proxyLevelArr = res.data || []
			})
		},
		_typeFilter(val, type) {
			const res = this[type].find((item) => item.code === String(val))
			return res?.description || '-'
		},
		filterRebateRatio(beginRate, endRate) {
			if (beginRate === endRate) {
				return `${this.decimalToMul(beginRate)}%` || '-'
			}
			beginRate = beginRate || beginRate === 0 ? beginRate : '-'
			endRate = endRate || endRate === 0 ? endRate : '-'
			return `${this.decimalToMul(beginRate)}% - ${this.decimalToMul(
				endRate
			)}%`
		},
		loadData() {
			this.loading = true

			this.queryData.signProxyName = ''
			this.queryData.parentProxyName = ''
			this.queryData.createAccount = ''
			if (this.selectSearchType === 1) {
				this.queryData.signProxyName = this.selectSearchVal
			} else if (this.selectSearchType === 2) {
				this.queryData.parentProxyName = this.selectSearchVal
			} else if (this.selectSearchType === 3) {
				this.queryData.createAccount = this.selectSearchVal
			}

			const [startTime, endTime] = this.loginTime || []
			let params = {
				...this.queryData,
				createStartTime: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				createEndTime: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined
			}
			params = {
				...this.getParams(params)
			}
			this.$api
				.getProxyContractList(filterEmptyParams(params))
				.then((res) => {
					const { records, total } = res.data || {}
					this.tableData = Array.isArray(records)
						? Object.freeze(records)
						: []
					this.total = total || 0
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
		},
		reset() {
			this.queryData = {
				contractStatus: undefined,
				contractType: undefined,
				createAccount: undefined,
				dataSources: undefined,
				effectStatus: undefined,
				parentProxyName: undefined,
				sginType: undefined,
				signProxyLevel: undefined,
				signProxyName: undefined,
				policyTypeConfigId: undefined
			}
			this.selectSearchType = 1
			this.selectSearchVal = ''
			this.pageNum = 1
			this.loginTime = [startTime(), endTime()]
			this.getPolicyTypeArr(true)
			this.loadData()
		},
		_changeTableSort({ column, prop, order }) {
			if (prop === 'loginTime') {
				prop = 1
			}
			this.queryData.orderKey = prop
			if (order === 'ascending') {
				// 升序
				this.queryData.orderType = 'asc'
			} else if (order === 'descending') {
				// 降序
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			this.loadData()
		},
		openEdit(rowData) {
			this.pageType = 'e'
			this.isEdit = true
			this.editData = Object.assign({}, rowData)
			if (this.editData.contractType === 1) {
				this.editData.commissionPolicyTypeId = this.editData.policyTypeConfigId
			} else {
				this.editData.rebatePolicyTypeId = this.editData.policyTypeConfigId
			}
			this.editData.contractType = [this.editData.contractType]
		},
		create() {
			this.pageType = 'e'
			// this.editData = {
			// 	contractType: [],
			// 	signedAccount: undefined,
			// 	proxyLevel: undefined,
			// 	parentProxyName: undefined
			// }
			this.isEdit = false
		},
		openSignDialog(rowData) {
			this.signDialog.visible = true
			this.signDialog.form.contractId = rowData.id
			this.signDialog.form.remark = undefined
		},
		closeSignDialog() {
			this.$refs.dialogForm.clearValidate()
		},
		handleSign() {
			this.$refs.dialogForm.validate((valid) => {
				if (valid) {
					this.signDialog.loading = true
					// 处理代签
					this.$api
						.acceptContractAPI({
							contractId: this.signDialog.form.contractId,
							remark: this.signDialog.form.remark
						})
						.then(() => {
							this.$message.success(
								this.$t('agent.signatory_success')
							)
							this.signDialog.loading = false
							this.signDialog.visible = false
							this.loadData()
						})
						.catch(() => {
							this.signDialog.loading = false
						})
				}
			})
		},
		openDetail(rowData) {
			this.pageType = 'd'
			this.detailData = Object.assign({}, rowData)

			let policyType
			if (rowData.policyTypeConfigId === 0) {
				policyType = { id: 0, policyType: this.$t('agent.custom') }
			} else {
				policyType = this.clonePolicyTypeArr?.find(
					(item) =>
						item.id === rowData.policyTypeConfigId &&
						rowData.contractType === item.contractType
				)
			}
			this.detailData.policyType = policyType || {}
		},
		back() {
			this.pageType = 'i'
			this.loadData()
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
	border-bottom: 1px solid #00000015;
}
::v-deep .tagheight .el-tag {
	height: 24px;
	line-height: 24px;
	min-width: 60px;
}
::v-deep .el-input-group__prepend {
	background-color: #fff;
}
.msgList {
	font-size: 14px;
	display: flex;
	p {
		margin-right: 20px;
		line-height: 24px;
	}
	&:last-child p {
		margin-bottom: 15px;
	}
}
</style>
